import { Injectable, Injector } from '@angular/core';
import { CanActivate, CanActivateChild, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { TokenService } from './token.service';
import { AuthConfig } from '../../config/auth.config';
import { check, toLogin } from './utils';

@Injectable()
export class TokenGuard implements CanActivate, CanActivateChild, CanLoad {

  constructor(
    private srv: TokenService,
    private injector: Injector,
    cfg: AuthConfig,
  ) {
    this.cfg = Object.assign(new AuthConfig(), cfg);
  }

  private cfg: AuthConfig;

  private process(url?: string): boolean {
    const res = check(this.srv.get());
    if (!res) {
      this.srv.redirect = url;
      toLogin(this.cfg, this.injector);
    }
    return res;
  }

  // lazy loading
  canLoad(): boolean {
    return this.process();
  }
  // all children route
  canActivateChild(): boolean {
    return this.process();
  }

  /**
   * validate logon
   * @param  {ActivatedRouteSnapshot} route [description]
   * @param  {RouterStateSnapshot}    state [description]
   * @return {boolean}                      [description]
   */
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.process(state.url);
  }

}
